//
//  WMMusic.m
//  WholeMusic
//
//  Created by quanxiong on 2018/2/12.
//  Copyright © 2018年 quanxiong. All rights reserved.
//

#import "WMMusic.h"
#import "NSString+WMUtils.h"
#import "NSFileManager+WMUtils.h"
#import <XQ_DAO/XQ_DAO.h>


@implementation WMQuality

+ (instancetype)qualityWithPrefix:(NSString *)prefix suffix:(NSString *)suffix {
    WMQuality *quality = [self new];
    quality.prefix = prefix;
    quality.suffix = suffix;
    return quality;
}

@end




@implementation WMSinger

+ (void)load {
    XQDBModelConfiguration *config = [XQDBModelConfiguration configuration];
    //    [config setPrimaryKey:XQDAO_SEL_TO_STRING(songmid)];
    [config addUniquesNotNull:@[XQDAO_SEL_TO_STRING(mid)]];
    [config addNotNullFields:@[XQDAO_SEL_TO_STRING(name)]];
    self.xq_modelConfiguration = config;
}

+ (NSDictionary *)modelCustomPropertyMapper {
    return @{@"ID" : @"id",};
}

- (NSString *)name {
    return [_name wm_stringByDecodingHTMLEntities];
}

@end




@implementation WMMusic

+ (void)load {
    XQDBModelConfiguration *config = [XQDBModelConfiguration configuration];
//    [config setPrimaryKey:XQDAO_SEL_TO_STRING(songmid)];
    [config addUniquesNotNull:@[XQDAO_SEL_TO_STRING(songmid)]];
    [config addNotNullFields:@[XQDAO_SEL_TO_STRING(type)]];
    self.xq_modelConfiguration = config;
}

+ (instancetype)queryWithMusic:(WMMusic *)music {
    return [self xq_queryWhere:XQDAO_SEL_TO_STRING(songmid)
                         equal:music.songmid];
}

+ (instancetype)queryWithSontmid:(NSString *)sontmid {
    return [self xq_queryWhere:XQDAO_SEL_TO_STRING(songmid)
                         equal:sontmid];
}

+ (NSDictionary *)modelCustomPropertyMapper {
    return @{@"SWITCH"  : @"switch",
             @"songmid" : @[@"songmid", @"id"],
             @"songname" : @[@"songname", @"name"],
//             @"songid" : @[@"songid", @"id"],
             };
}

+ (NSDictionary *)modelContainerPropertyGenericClass {
    return @{@"singer" : [WMSinger class],};
}

- (NSString *)albumname {
    return [_albumname wm_stringByDecodingHTMLEntities];
}

- (NSString *)songname {
    return [_songname wm_stringByDecodingHTMLEntities];
}

- (CGFloat)fileSize {
    NSError *error;
    NSDictionary<NSFileAttributeKey, id> *fileAttributes =
    [[NSFileManager defaultManager] attributesOfItemAtPath:[self filePath] error:&error];
    
    long long length = [fileAttributes fileSize];
    CGFloat fileSize = length / 1024.0 / 1024.0;
    if (error) {
        NSLog(@"%@", error);
    }
    return fileSize;
}
- (NSString *)filePathWithFileName:(NSString *)filename {
    NSString *directory = [self defaultFileDirectory];
    NSString *filePath = [directory stringByAppendingPathComponent:filename];
    return filePath;
}

- (NSString *)filePath {
    return [self filePathWithFileName:self.fileName];
}

- (NSString *)defaultFilePath {
    return [self filePathWithFileName:[self defaultFileName]];
}

- (NSString *)defaultFileDirectory {
    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [documents firstObject];
    NSString *dirName = @"qq_music";
    if (self.type.length > 0) {
        dirName = self.type;
    }
    NSString *directory = [documentPath stringByAppendingPathComponent:dirName];
    [NSFileManager createDirectorIfNeed:directory];
    return directory;
}

- (NSString *)defaultFileName {
    return [self fileNameForQuality:WMMusicQuality128 qualityFirst:NO];
}

- (WMQuality *)defaultQuality {
    return [self guessQualityForQuality:WMMusicQuality128 qualityFirst:NO];
}

- (NSString *)fileNameForQuality:(WMMusicQuality)quality qualityFirst:(BOOL)qualityFirst {
    WMQuality *qq = [self guessQualityForQuality:quality qualityFirst:qualityFirst];
    NSString *mid = self.songmid;
    NSString *fileName = [NSString stringWithFormat:@"%@%@.%@", qq.prefix, mid, qq.suffix];
    return fileName;
}

- (WMQuality *)guessQualityForQuality:(WMMusicQuality)quality qualityFirst:(BOOL)qualityFirst {
    //flac > wav > ogg > ape > aac > mp3-320 > mp3-128
    
    static NSDictionary<NSNumber *, WMQuality *> *s_qualityToResult;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        s_qualityToResult = @{@(WMMusicQuality128):[WMQuality qualityWithPrefix:@"M500" suffix:@"mp3"],
                              @(WMMusicQuality320):[WMQuality qualityWithPrefix:@"M800" suffix:@"mp3"],
                              @(WMMusicQualityApe):[WMQuality qualityWithPrefix:@"C400" suffix:@"m4a"],
                              @(WMMusicQualityOgg):[WMQuality qualityWithPrefix:@"C400" suffix:@"m4a"],
                              @(WMMusicQualityFlac):[WMQuality qualityWithPrefix:@"C400" suffix:@"m4a"],};
    });
   NSDictionary<NSNumber *, NSNumber *> *
    qualityToSize = @{@(WMMusicQuality128):@(self.size128),
                      @(WMMusicQuality320):@(self.size320),
                      @(WMMusicQualityApe):@(self.sizeape),
                      @(WMMusicQualityOgg):@(self.sizeogg),
                      @(WMMusicQualityFlac):@(self.sizeflac),};
    
    if (qualityToSize[@(quality)].integerValue > 0) {
        return s_qualityToResult[@(quality)];
    }
    
    NSArray<NSNumber *> *sizePropList = @[@(self.size128),
                                          @(self.size320),
                                          @(self.sizeape),
                                          @(self.sizeogg),
                                          @(self.sizeflac),];
    __block WMQuality *b_result;
    assert(sizePropList.count == qualityToSize.count);
    if (qualityFirst) {
        for (NSInteger idx = sizePropList.count - 1; idx > 0; --idx) {
            if (sizePropList[idx].integerValue != 0) {
                b_result = s_qualityToResult[@(idx)];
                break;
            }
        }
    } else {
        for (NSInteger idx = 0; idx < sizePropList.count; ++idx) {
            if (sizePropList[idx].integerValue != 0) {
                b_result = s_qualityToResult[@(idx)];
                break;
            }
        }
    }
    return b_result;
}

@end
